import pickle, base64
from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, user):
    """
    合并请求用户的购物车数据,将未登录保存在cookie里的保存到redis中
    遇到cookie和redis中出现相同的商吕时以cookie数据为主,覆盖redis中的数据
    :param request: 用户的请求对象
    :param user: 当前登录用户
    :param response: 响应对象,用于清除购物车cookie
    :return: response
    """
    # 获取cookie中的购物车
    cookie_cart_str = request.COOKIES.get('cart')
    # 读取redis中的购物车数据
    redis_conn = get_redis_connection('cart')
    redis_cart_dict = redis_conn.hgetall('cart_%s' % user.id)
    redis_cart_selected = redis_conn.smembers('selected_%s' % user.id)
    if cookie_cart_str:

        # 解析cookie购物车数据
        cookie_cart_dict = pickle.loads(base64.b64decode(cookie_cart_str.encode()))

        # 合并cookie到redis(核心代码)
        for sku_id, cookie_dict in cookie_cart_dict.items():
            # 将cookie_dict合并到redis_cart_dict
            redis_cart_dict[sku_id] = cookie_dict['count']
            # 将sku_id 合并到redis_cart_selected
            if cookie_dict['selected']:
                redis_cart_selected.add(sku_id)

        # 需要将合并的数据同步到redis
        pl = redis_conn.pipeline()
        pl.hmset('cart_%s' % user.id, redis_cart_dict)
        pl.sadd('selected_%s' % user.id, *redis_cart_selected)
        pl.execute()
    return redis_cart_dict, redis_cart_selected
